package org.abettor.nookinfo.photo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.abettor.nookinfo.AddressConstant;
import org.abettor.nookinfo.R;
import org.abettor.nookinfo.ads.YoumiManager;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

/**
 * 显示每天图片的列表
 */
public class PhotoThumbnail extends Activity {
	private YoumiManager youmi = new YoumiManager(this);
	private static final int THUMBNAIL_WIDTH = 100;
	private static final int THUMBNAIL_HEIGHT = 100;
	private float scaleRatio;
	public static final String PHOTO_DAILY_ID = "PHOTO_DAILY_ID";// 参数,所属日期的ID
	public static final String PHOTO_DAILY_NAME = "PHOTO_DAILY_NAME";// 参数,所属日期
	private ProgressDialog progressDialog = null;// 进度条对话框
	private int[] items;
	private static final int REFRESHED = 1;// 菜单更新已完成事件
	private static final int FAILED = 2;// 菜单更新失败时间
	private boolean picLoading = false;//检查现在是否正在加载缩略图
	private Worker worker = null;// 网络访问线程
	private int id;// 要更新的Daily的id
	private int category;
	private PhotoViewAdapter viewAdapter;// 需要更新的adapter

	// 图片点击的监听器
	public class ItemClickListener implements AdapterView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			Bundle extras = new Bundle();
			extras.putInt(PhotoView.PHOTO_ID_INDEX, position);
			extras.putIntArray(PhotoView.PHOTO_ID_LIST, items);
			extras.putInt(PhotoDailyList.PHOTO_CATEGORY_ID, category);
			Intent viewImageIntent = new Intent();
			viewImageIntent.putExtras(extras);
			viewImageIntent.setClass(PhotoThumbnail.this, PhotoView.class);
			startActivity(viewImageIntent);
		}
	}

	// 更新对话框的类
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == REFRESHED) {
				GridView g = (GridView) findViewById(R.id.photoThumbnail);
				viewAdapter = new PhotoViewAdapter(PhotoThumbnail.this);
				g.setAdapter(viewAdapter);
				// 增加选项点击的操作
				g.setOnItemClickListener(new ItemClickListener());
				// 启动更新图片的线程
				Thread thread = new Thread(new PhotoDetailUpdateThread());
				thread.start();

				//	按照一定的概率显示广告
				Random rand = new Random(System.currentTimeMillis());
				int val = rand.nextInt(99);
				if(val < 20)
				{
					youmi.showYoumi(YoumiManager.Position.middle, Color.WHITE, Color.BLACK, 0xAA);
				}
			} else if (msg.what == FAILED) {
				Builder builder = new Builder(PhotoThumbnail.this);
				builder.setTitle(R.string.photo_thumbnail_fail_title);
				builder.setMessage(R.string.photo_thumbnail_fail_content);
				builder.setPositiveButton(R.string.photo_thumbnail_fail_btn_ok,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(
									DialogInterface dialoginterface, int i) {
								dialoginterface.dismiss();
							}
						});
				builder.show();
			}
			super.handleMessage(msg);
		}
	};
	// 更新图片的操作
	private Handler drawImageHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Bundle bundle = msg.getData();
			int key = bundle.getInt("key");
			Bitmap bit = bitmapMap.get(String.valueOf(key));
			GridView g = (GridView) findViewById(R.id.photoThumbnail);
			ImageView image = (ImageView) g.getChildAt(key);
			image.setMinimumWidth(THUMBNAIL_WIDTH);
			image.setMinimumHeight(THUMBNAIL_HEIGHT);
			image.setMaxWidth(THUMBNAIL_WIDTH);
			image.setMaxHeight(THUMBNAIL_HEIGHT);
			image.setImageBitmap(bit);
			viewAdapter.notifyDataSetChanged();
		}
	};

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.photo_thumbnail);
		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		id = extras.getInt(PHOTO_DAILY_ID);
		String date = extras.getString(PHOTO_DAILY_NAME);
		String categoryName = extras.getString(PhotoDailyList.PHOTO_CATEGORY_NAME);
		category = extras.getInt(PhotoDailyList.PHOTO_CATEGORY_ID);
		String label = getString(R.string.photo_thumbnail_label);
		label = label.replace("REPL1", categoryName).replace("REPL2", date);
		setTitle(label);

		onRefreshClicked(null);

		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		scaleRatio = dm.density;
	}

	/**
	 * 刷新按钮点击事件
	 */
	public void onRefreshClicked(View v)
	{
		//	正在显示加载图片的过程中，不能刷新！
		synchronized (this)
		{
			if(picLoading)
			{
				return;
			}
		}

		if(v != null)
		{
			//	删除GridView里的所有对象
			GridView gridView = (GridView) findViewById(R.id.photoThumbnail);
			gridView.removeViews(0, gridView.getChildCount());

			//	删除已经存在的文件（如果有的话）
			if(items != null)
			{
				for(int item : items)
				{
					String path = AddressConstant.PHOTO_THUMBNAIL_IMAGE_LOCAL.replace("ID", item + "");
					File file = new File(path);
					if(file.exists())
					{
						file.delete();
					}
				}
			}
		}

		// 显示更新的对话框
		progressDialog = new ProgressDialog(this);
		progressDialog.setCancelable(true);
		progressDialog.setTitle(R.string.photo_thumbnail_progress_title);
		progressDialog.setMessage(getText(R.string.photo_thumbnail_progress_content));
		progressDialog.setButton(
				getText(R.string.photo_thumbnail_progress_btn_cancel),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialoginterface, int i) {
						worker.kill();
					}
				});
		progressDialog.show();
		worker = new Worker();
		worker.start();
	}

	/**
	 * 返回按钮点击事件
	 */
	public void onReturnClicked(View v)
	{
		finish();
	}

	// 图片显示的适配器
	private class PhotoViewAdapter extends BaseAdapter {
		private Context mContext;

		public PhotoViewAdapter(Context c) {
			mContext = c;
		}

		@Override
		public int getCount() {
			return items.length;
		}

		@Override
		public Object getItem(int position) {
			return items[position];
		}

		@Override
		public long getItemId(int position) {
			return items[position];
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView;
			if (convertView == null) {
				imageView = new ImageView(mContext);
				imageView.setLayoutParams(new GridView.LayoutParams((int) (THUMBNAIL_WIDTH * scaleRatio), (int) (THUMBNAIL_HEIGHT * scaleRatio)));
				imageView.setScaleType(ImageView.ScaleType.FIT_XY);
				//imageView.setPadding(1, 1, 1, 1);
			} else {
				imageView = (ImageView) convertView;
			}
			Bitmap bit = bitmapMap.get(String.valueOf(position));
			imageView.setImageBitmap(bit);
			return imageView;
		}

	}

	// 解析图片id的列表
	private int[] fetchItems() throws Exception {
		List<Integer> list = new ArrayList<Integer>();
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		String url = AddressConstant.PHOTO_THUMBNAIL.replace("ID", id + "");
		Document doc = db.parse(url);
		NodeList nodeList = doc.getElementsByTagName("image");
		int len = nodeList.getLength();
		for (int i = 0; i < len; i++) {
			Node node = nodeList.item(i);
			String nodeName = node.getNodeName();
			if ("image".equals(nodeName)) {
				String id = node.getTextContent();
				int val = Integer.parseInt(id);
				list.add(val);
			}
		}
		int[] array = new int[list.size()];
		for(int i = 0; i < list.size(); i ++)
		{
			array[i] = list.get(i);
		}

		return array;
	}

	/**
	 * 网络连接并更新菜单信息的工作者线程
	 * @author shawn
	 * 
	 */
	private class Worker extends Thread {
		// 线程是否为意外退出的标记
		private boolean cancel = false;

		/**
		 * 强制杀死工作者线程
		 */
		public void kill() {
			cancel = true;
			this.interrupt();
		}

		@Override
		public void run() {
			try {
				// 此处访问网络并获取图片对象列表
				items = fetchItems();

				// 关闭进度对话框并通知界面更新
				progressDialog.dismiss();
				if (!cancel) {
					// 在非意外中断情况下才更新界面
					Message msg = new Message();
					msg.what = REFRESHED;
					handler.sendMessage(msg);
				} else {
					// 意外中断的情况下，显示错误对话框
					Message msg = new Message();
					msg.what = FAILED;
					handler.sendMessage(msg);
				}
			} catch (Exception e) {
				items = new int[0];
				try { progressDialog.dismiss(); } catch (Exception ex) { };

				// 意外中断的情况下，显示错误对话框
				Message msg = new Message();
				msg.what = FAILED;
				handler.sendMessage(msg);
				Log.d(this.getClass().getName(), "", e);
			}
		}
	}

	// 更新图片的bitmap
	private Map<String, Bitmap> bitmapMap = new HashMap<String, Bitmap>();
	// 更新图片的线程
	private class PhotoDetailUpdateThread implements Runnable {
		@Override
		public void run() {
			//	正在显示加载图片的过程中，不能刷新！
			synchronized (PhotoThumbnail.this)
			{
				PhotoThumbnail.this.picLoading = true;
			}
			processPic();
			synchronized (PhotoThumbnail.this)
			{
				PhotoThumbnail.this.picLoading = false;
			}
		}

		// 处理图片的加载
		public void processPic() {
			int count = 0;
			for (int item : items)
			{
				Bitmap bitmap = null;
				boolean localValid = false;
				String local = AddressConstant.PHOTO_THUMBNAIL_IMAGE_LOCAL.replace("ID", item + "");
				File file = new File(local);
				if(file.exists())
				{
					InputStream is = null;
					try
					{
						is = new FileInputStream(file);
						bitmap = BitmapFactory.decodeStream(is);
						if(bitmap == null)
						{
							//	文件格式有问题，删掉
							is.close();
							is = null;
							file.delete();
							localValid = false;
						}
						else
						{
							localValid = true;
						}
					}
					catch(Exception e)
					{
						localValid = false;
						Log.d(this.getClass().getName(), "", e);
					}
					finally
					{
						if(is != null)
						{
							try { is.close(); } catch (Exception e) { };
						}
					}
				}

				if(! localValid)
				{
					String str = AddressConstant.PHOTO_THUMBNAIL_IMAGE.replace("ID", item + "");
					bitmap = readAndSavePic(str, local);
				}

				synchronized (bitmapMap) {
					bitmapMap.put(String.valueOf(count), bitmap);
				}

				// 发送消息
				Message msg = new Message();
				Bundle data = new Bundle();
				data.putInt("key", count);
				drawImageHandler.sendMessage(msg);
				count++;
			}
		}
	}

	// 读取图片
	private Bitmap readAndSavePic(String str, String local)
	{
		InputStream is = null;
		FileOutputStream os = null;
		try
		{
			URL url = new URL(str);
			is = url.openStream();
			Bitmap bitmap = BitmapFactory.decodeStream(is);

			File file = new File(local);
			File dir = file.getParentFile();
			if(! dir.exists())
			{
				dir.mkdirs();
			}

			if(file.exists())
			{
				file.delete();
			}

			file.createNewFile();
			os = new FileOutputStream(file);
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);

			return bitmap;
		}
		catch (Exception e)
		{
			Log.d(this.getClass().getName(), "", e);
		}
		finally
		{
			if (is != null)
			{
				try { is.close(); } catch (Exception e) { };
			}
			if(os != null)
			{
				try { os.close(); } catch (Exception e) { };
			}
		}

		return null;
	}
}
